package com.learning.netease.distributed.lock.zk.zklock.improve;

import com.learning.netease.distributed.lock.zk.OrderCodeGenerator;
import com.learning.netease.distributed.lock.zk.OrderService;

import java.util.concurrent.locks.Lock;

/**
 * ClassName: OrderServiceImplWithLock
 * Description: 加锁的订单服务
 * Date: 2019/3/20 13:43 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class OrderServiceImplWithZkImproveLock implements OrderService {

    /**
     * 用 static 修饰来模拟共用一个订单编号生成服务
     */
    private static OrderCodeGenerator generator = new OrderCodeGenerator();

    private Lock lock = new ZkDistributedImproveLock("localhost:2181", "/zk-distributed-lock");

    @Override
    public void createOrder() {
        String orderCode;
        // 基于临时有序节点获取实现
        try {
            // 加锁
            lock.lock();
            orderCode = generator.getOrderCode();
        } finally {
            lock.unlock();
        }

        System.out.println(Thread.currentThread().getName() + " ***************** >" + orderCode);

        // 其他业务处理 ... ...
    }
}
